package marek.barak.classes;


import java.io.File;
import java.util.ArrayList;
import java.util.List;


import java.io.FileNotFoundException;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class Connection {
	private static Connection instance;
	private final  File uLocation;
	

	private Connection(){
		uLocation = new File("."+File.separator+"Users");
		if(!uLocation.exists())
			uLocation.mkdir();
	
		
	}
	public static Connection getInstance(){
		if(instance==null)
			instance = new Connection();
		return instance;
	}
	@SuppressWarnings("unchecked")
	public List<User> loadUsers() throws IOException,ClassNotFoundException{
		List<User> users = null;
		if((new File(uLocation.getAbsoluteFile()+File.separator+"users.dt")).exists()){
			ObjectInputStream in = null;
			try{
				in = new  ObjectInputStream(new FileInputStream(uLocation.getAbsoluteFile()+File.separator+"users.dt"));
				users = (ArrayList<User>) in.readObject();
			}finally{
				if(in!=null)
					in.close();
			}
		}else
			users = new ArrayList<User>();
		return users;
		};
		
	public void saveUsers(List<User> u) throws IOException{
	ObjectOutputStream o = null;
		try{
			o = new ObjectOutputStream(new FileOutputStream(uLocation.getAbsoluteFile()+File.separator+"users.dt"));
			o.writeObject(u);
		}finally{
			if(o!=null)
				o.close();
			}
	
		}
	
	public int loadCurentUser()throws IOException,ClassNotFoundException{
		Integer curent =-1;
		ObjectInputStream in =null;
		if((new File(uLocation.getAbsoluteFile()+File.separator+"curent.dt")).exists())
		try{
			in = new ObjectInputStream(new FileInputStream(uLocation.getAbsoluteFile()+File.separator+"curent.dt"));
			curent = (Integer)in.readObject();
		}
		finally{
			if(in!=null){
				in.close();
			}
		}
		return curent;
		
	}
	public void saveCurentUser(Integer c) throws FileNotFoundException, IOException{
		ObjectOutputStream o = null;
		try{
			o = new ObjectOutputStream(new FileOutputStream(uLocation.getAbsoluteFile()+File.separator+"curent.dt"));
			o.writeObject(c);
			System.out.println("Saved");
		}finally{
			if(c!=null)
				o.close();
		}
	}

}